package com.btshop.goods.service.impl;

import java.util.Date;
import java.util.List;
import java.util.Map;

import com.btshop.goods.pojo.*;
import com.btshop.goods.service.BrandService;
import com.btshop.goods.service.CategoryService;
import com.util.DateUtil;
import com.util.JsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.btshop.goods.constant.GoodsConstant;
import com.btshop.goods.mapper.SpuMapper;
import com.btshop.goods.service.SkuService;
import com.btshop.goods.service.SpuService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.util.IdWorker;
import org.springframework.util.StringUtils;

/**
 * @ClassName: SpuServiceImpl
 * @description: Spu业务层接口实现类
 * @author: 李东
 * @Date: 2020-7-20
 */
@Service
public class SpuServiceImpl implements SpuService {


    @Autowired
    private IdWorker idWorker;
    @Autowired
    private SpuMapper spuMapper;
    @Autowired
    private SkuService skuService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private BrandService brandService;


    /**
     * 批量上架
     * @param ids
     */
    @Transactional(rollbackFor = Throwable.class)
    @Override
    public void putMany(List<Long> ids) {
        SpuExample example = new SpuExample();
        SpuExample.Criteria criteria = example.createCriteria();
        criteria.andIdIn(ids);
        criteria.andIsDeleteEqualTo(GoodsConstant.NOT_DELETE);
        criteria.andStatusEqualTo(GoodsConstant.STATUS_SUCCESS);

        Spu spu = new Spu();
        spu.setIsMarketable(GoodsConstant.MARKETABLE_UP);

        spuMapper.updateByExampleSelective(spu,example);
    }

    /**
     * 商品上架
     * @param spuId
     */
    @Override
    public void put(Long spuId) {
        //查询商品
        Spu spu = spuMapper.selectByPrimaryKey(spuId);
        //判断商品是否符合审核条件
        if(spu.getIsDelete().equals(GoodsConstant.DELETE)){
            throw new RuntimeException("不能对已删除的商品进行上架！");
        }
        if(spu.getStatus().equals(GoodsConstant.STATUS_FAIL)){
            throw new RuntimeException("不能对审核不通过的商品进行上架！");
        }

        //审核商品
        spu.setIsMarketable(GoodsConstant.MARKETABLE_UP);

        spuMapper.updateByPrimaryKey(spu);
    }

    /**
     * 商品下架
     */
    @Transactional(rollbackFor = Throwable.class)
    @Override
    public void pull(Long spuId) {
        //查询商品
        Spu spu = spuMapper.selectByPrimaryKey(spuId);
        //判断商品是否符合审核条件
        if(spu.getIsDelete().equals(GoodsConstant.DELETE)){
            throw new RuntimeException("不能对已删除的商品进行下架！");
        }

        //审核商品
        spu.setIsMarketable(GoodsConstant.MARKETABLE_DOWN);

        spuMapper.updateByPrimaryKey(spu);
    }

    /**
     * 商品审核
     * @param spuId
     */
    @Transactional(rollbackFor = Throwable.class)
    @Override
    public void audit(Long spuId,String status) {
        //查询商品
        Spu spu = spuMapper.selectByPrimaryKey(spuId);
        //判断商品是否符合审核条件
        if(spu.getIsDelete().equals(GoodsConstant.DELETE)){
            throw new RuntimeException("不能对已删除的商品进行审核！");
        }

        if(status.equals(GoodsConstant.STATUS_SUCCESS)){
            spu.setStatus(status);
            spu.setIsMarketable(GoodsConstant.MARKETABLE_UP);
        }

        if(status.equals(GoodsConstant.STATUS_FAIL)){
            spu.setStatus(status);
            spu.setIsMarketable(GoodsConstant.MARKETABLE_DOWN);
        }

        spuMapper.updateByPrimaryKey(spu);
    }

    /**
     * 根据spuId查询商品信息
     * @param spuId
     * @return
     */
    @Override
    public Goods findGoodsBySpuId(Long spuId) {
        //spu信息
        Spu spu = spuMapper.selectByPrimaryKey(spuId);
        //sku信息
        Sku sku = new Sku();
        sku.setSpuId(spuId);
        List<Sku> skuList = skuService.findList(sku);

        Goods goods = new Goods();
        goods.setSpu(spu);
        goods.setSkuList(skuList);

        return goods;
    }

    /**
     * 添加商品信息
     * 
     * @param goods
     */
    @Transactional(rollbackFor = Throwable.class)
    @Override
    public void saveGoods(Goods goods) {
        //获取spu
        Spu spu = goods.getSpu();
        //判断spu id 是否有值，如果有值，修改，反之新增
        if(null == spu.getId()){
            // 增加 spu信息
            spu.setId(idWorker.nextId());
            spu.setIsDelete(GoodsConstant.NOT_DELETE);
            spu.setIsMarketable(GoodsConstant.MARKETABLE_DOWN);
            spu.setStatus(GoodsConstant.STATUS_NONE);
            spu.setCreateTime(DateUtil.getNowDate());
            spu.setUpdateTime(DateUtil.getNowDate());
            spu.setOptimistic(0);
            spuMapper.insertSelective(spu);
        }else {
            spuMapper.updateByPrimaryKeySelective(spu);
            //删除sku
            skuService.deleteBySpuId(spu.getId());
        }


        //查询三级分类
        Category category = categoryService.findById(spu.getCategory3Id());
        //查询品牌
        Brand brand = brandService.findById(spu.getBrandId());

        // Sku List 增加
        List<Sku> skuList = goods.getSkuList();
        for (Sku sku : skuList) {
            //封装sku名称 sku名称 = sku名称 + 商品参数规格
            String skuName = sku.getName();
            String spec = sku.getSpec();
            if(StringUtils.isEmpty(spec)){
                spec="{}";
            }
            //商品参数规格
            Map<String, String> jsonMap = JsonUtils.parseMap(spec, String.class, String.class);
            for (Map.Entry<String, String> entry : jsonMap.entrySet()) {
                skuName+=" "+entry.getValue();
            }

            sku.setName(skuName);
            sku.setSpuId(spu.getId());
            sku.setCreateTime(DateUtil.getNowDate());
            sku.setUpdateTime(DateUtil.getNowDate());
            sku.setCategoryId(category.getId());//三级分类
            sku.setCategoryName(category.getName());//三级分类
            sku.setBrandName(brand.getName());//品牌名称
            skuService.add(sku);
        }

    }

    /**
     * Spu条件+分页查询
     * 
     * @param spu 查询条件
     * @param page 页码
     * @param size 页大小
     * @return 分页结果
     */
    @Override
    public PageInfo<Spu> findPage(Spu spu, int page, int size) {
        // 分页
        PageHelper.startPage(page, size);
        // 搜索条件构建
        SpuExample example = createExample(spu);
        // 执行搜索
        return new PageInfo<Spu>(spuMapper.selectByExample(example));
    }

    /**
     * Spu分页查询
     * 
     * @param page
     * @param size
     * @return
     */
    @Override
    public PageInfo<Spu> findPage(int page, int size) {
        // 静态分页
        PageHelper.startPage(page, size);
        // 分页查询
        return new PageInfo<Spu>(this.buildSelectAll());
    }

    /**
     * Spu条件查询
     * 
     * @param spu
     * @return
     */
    @Override
    public List<Spu> findList(Spu spu) {
        // 构建查询条件
        SpuExample example = createExample(spu);
        // 根据构建的条件查询数据
        return spuMapper.selectByExample(example);
    }


    /**
     * Spu构建查询对象
     * 
     * @param spu
     * @return
     */
    public SpuExample createExample(Spu spu) {
        SpuExample example = new SpuExample();
        SpuExample.Criteria criteria = example.createCriteria();
        if (spu != null) {
            // 主键
            if (!StringUtils.isEmpty(spu.getId())) {
                criteria.andIdEqualTo(spu.getId());
            }
            // 货号
            if (!StringUtils.isEmpty(spu.getSn())) {
                criteria.andSnEqualTo(spu.getSn());
            }
            // SPU名
            if (!StringUtils.isEmpty(spu.getName())) {
                criteria.andNameLike("%" + spu.getName() + "%");
            }
            // 副标题
            if (!StringUtils.isEmpty(spu.getCaption())) {
                criteria.andCaptionEqualTo(spu.getCaption());
            }
            // 品牌ID
            if (!StringUtils.isEmpty(spu.getBrandId())) {
                criteria.andBrandIdEqualTo(spu.getBrandId());
            }
            // 一级分类
            if (!StringUtils.isEmpty(spu.getCategory1Id())) {
                criteria.andCategory1IdEqualTo(spu.getCategory1Id());
            }
            // 二级分类
            if (!StringUtils.isEmpty(spu.getCategory2Id())) {
                criteria.andCategory2IdEqualTo(spu.getCategory2Id());
            }
            // 三级分类
            if (!StringUtils.isEmpty(spu.getCategory3Id())) {
                criteria.andCategory3IdEqualTo(spu.getCategory3Id());
            }
            // 模板ID
            if (!StringUtils.isEmpty(spu.getTemplateId())) {
                criteria.andTemplateIdEqualTo(spu.getTemplateId());
            }
            // 运费模板id
            if (!StringUtils.isEmpty(spu.getFreightId())) {
                criteria.andFreightIdEqualTo(spu.getFreightId());
            }
            // 图片
            if (!StringUtils.isEmpty(spu.getImage())) {
                criteria.andImageEqualTo(spu.getImage());
            }
            // 图片列表
            if (!StringUtils.isEmpty(spu.getImages())) {
                criteria.andImagesEqualTo(spu.getImages());
            }
            // 售后服务
            if (!StringUtils.isEmpty(spu.getSaleService())) {
                criteria.andSaleServiceEqualTo(spu.getSaleService());
            }
            // 规格列表
            if (!StringUtils.isEmpty(spu.getSpecItems())) {
                criteria.andSpecItemsEqualTo(spu.getSpecItems());
            }
            // 参数列表
            if (!StringUtils.isEmpty(spu.getParaItems())) {
                criteria.andParaItemsEqualTo(spu.getParaItems());
            }
            // 销量
            if (!StringUtils.isEmpty(spu.getSaleNum())) {
                criteria.andSaleNumEqualTo(spu.getSaleNum());
            }
            // 评论数
            if (!StringUtils.isEmpty(spu.getCommentNum())) {
                criteria.andCommentNumEqualTo(spu.getCommentNum());
            }
            // 是否上架,0已下架，1已上架
            if (!StringUtils.isEmpty(spu.getIsMarketable())) {
                criteria.andIsMarketableEqualTo(spu.getIsMarketable());
            }
            // 是否启用规格
            if (!StringUtils.isEmpty(spu.getIsEnableSpec())) {
                criteria.andIsEnableSpecEqualTo(spu.getIsEnableSpec());
            }
            // 是否删除,0:未删除，1：已删除
            if (!StringUtils.isEmpty(spu.getIsDelete())) {
                criteria.andIsDeleteEqualTo(spu.getIsDelete());
            }
            // 审核状态，0：未审核，1：已审核，2：审核不通过
            if (!StringUtils.isEmpty(spu.getStatus())) {
                criteria.andStatusEqualTo(spu.getStatus());
            }
            // 创建时间
            if (!StringUtils.isEmpty(spu.getCreateTime())) {
                criteria.andCreateTimeEqualTo(spu.getCreateTime());
            }
            // 更新时间
            if (!StringUtils.isEmpty(spu.getUpdateTime())) {
                criteria.andUpdateTimeEqualTo(spu.getUpdateTime());
            }
            // 乐观锁版本号
            if (!StringUtils.isEmpty(spu.getOptimistic())) {
                criteria.andOptimisticEqualTo(spu.getOptimistic());
            }
            // 备注字段
            if (!StringUtils.isEmpty(spu.getRemark())) {
                criteria.andRemarkEqualTo(spu.getRemark());
            }
        }
        return example;
    }

    /**
     * 删除
     * 
     * @param id
     */
    @Transactional(rollbackFor = Throwable.class)
    @Override
    public void delete(Long id) {
        spuMapper.deleteByPrimaryKey(id);
    }

    /**
     * 修改Spu
     * 
     * @param spu
     */
    @Transactional(rollbackFor = Throwable.class)
    @Override
    public void update(Spu spu) {
        spuMapper.updateByPrimaryKey(spu);
    }

    /**
     * 增加Spu
     * 
     * @param spu
     */
    @Transactional(rollbackFor = Throwable.class)
    @Override
    public void add(Spu spu) {
        // 设置主键值
        spu.setId(idWorker.nextId());
        spu.setIsDelete(GoodsConstant.NOT_DELETE);
        spu.setIsMarketable(GoodsConstant.MARKETABLE_UP);
        spu.setStatus(GoodsConstant.STATUS_NONE);
        spu.setCreateTime(new Date());
        spu.setUpdateTime(new Date());
        spu.setOptimistic(0);
        spuMapper.insertSelective(spu);
    }

    /**
     * 根据ID查询Spu
     * 
     * @param id
     * @return
     */
    @Override
    public Spu findById(Long id) {
        return spuMapper.selectByPrimaryKey(id);
    }

    /**
     * 查询Spu全部数据
     * 
     * @return
     */
    @Override
    public List<Spu> findAll() {
        return this.buildSelectAll();
    }

    public List<Spu> buildSelectAll() {
        return spuMapper.selectByExample(null);
    }
}
